package de.ghost23.util;

import java.util.HashMap;
import java.util.Map;

public class ParameterAnalyzer {
	
	private String[] _flags;
    private int _flagsIndex = 0;

    public String[] getFlags() {
		return _flags.clone();
    }

    public Boolean flagIsSet(String flag) {
        for (int i = 0; i < _flags.length; i++) {
            if (_flags[i] == flag) {
                return true;
            }
        }
        return false;
    }

    private HashMap<String, String> _configurators;

    public HashMap<String, String> getConfigurators() {

    	return _configurators;
    }

    private String[] _standaloneValues;
    private int _standaloneValuesIndex = 0;

    public String[] getStandaloneValues() {
    	return _standaloneValues.clone();
    }

    public ParameterAnalyzer(String[] parameters) {

        analyzeParameterString(parameters);
    }

    private void analyzeParameterString(String[] parameters) {

        _flags = new String[parameters.length];
        _configurators = new HashMap<String, String>();
        _standaloneValues = new String[parameters.length];

        for (int i = 0; i < parameters.length; i++) {

            // Found a flag or configurator
            if (parameters[i].charAt(0) == '-') {

                if (i + 1 < parameters.length && parameters[i + 1].charAt(0) != '-') {

                    // Found a real configurator
                    _configurators.put(parameters[i].substring(1), parameters[i + 1]);
                    i++;
                }
                else {

                    // Found a simple flag
                    _flags[_flagsIndex++] = parameters[i].substring(1);
                }
            }
            else {

                // Found a standalone value
                _standaloneValues[_standaloneValuesIndex++] = parameters[i];
            }
        }
    }

    public String ToString() {

        String result = "Parameter object: \n\n";
        result += "flags: \n";
        for (int i = 0; i < _flagsIndex; i++) {
            result += "\t" + _flags[i] + "\n";
        }
        result += "\nconfigurators:\n";
        for (Map.Entry<String, String> de: _configurators.entrySet()) {
            result += "\t" + de.getKey() + ":\t" + de.getValue() + "\n";
        }
        result += "\nstandaloneValues:\n";
        for (int i = 0; i < _standaloneValuesIndex; i++) {
            result += "\t" + _standaloneValues[i] + "\n";
        }

        return result;
    }
}